package com.hxx.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.hxx.domain.TUser;
import com.hxx.service.UserService;
import com.hxx.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("*.do")
public class UserController extends HttpServlet {
    //创建UserService对象
    private UserService userService = new UserServiceImpl();
    @Override
    protected void service(HttpServletRequest request
            , HttpServletResponse response) throws ServletException, IOException {
        String flag = "";
        //获取前端的json字符串
        String readLine = request.getReader().readLine();
        //获取传递的flag标识
        JSONObject jsonObject = JSON.parseObject(readLine);
        String strFlag = "";
        if (jsonObject!=null){
            if (jsonObject.getString("flag")!=null) {
                strFlag = jsonObject.getString("flag");
                //获取user对象
                TUser tUser = JSON.parseObject(readLine, TUser.class);
                //判断执行的功能
                flag = strFlag;
                if ("save".equals(flag)) {
                    userService.save(tUser);
                    return;
                } else if ("del".equals(flag)) {
                    userService.delete(tUser.getId());
                    return;
                } else if ("update".equals(flag)) {
                    userService.update(tUser);
                    return;
                }
            }
        }
        //分页显示
        int pageNo = 1;
        int pageSize = 3;
        if(jsonObject.getInteger("pageNo")!=null &&
                jsonObject.getInteger("pageSize")!=null){
            pageNo = jsonObject.getInteger("pageNo");
            pageSize = jsonObject.getInteger("pageSize");
        }
        List<TUser> list = userService.findByPage(pageNo, pageSize);
        //写到前端
        response.setContentType("text/html;charset=utf-8");
        //创建一个map集合，存放数据
        Map<String,Object> map = new HashMap<>();
        map.put("list",list);
        map.put("total",userService.getRows());
        //将map集合转换为json字符串
        response.getWriter().write(JSON.toJSONString(map));
    }
}























